package com.yiwenup.leetcode.hot;

import com.yiwenup.leetcode.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @PROJECT struct-algorithm
 * @PACKAGE com.yiwenup.leetcode.hot
 * @Author yiwenup
 * @Date 2022-03-10 21:36:15
 * <p>
 * @DESCRIPTION https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 * <pre>
 *     执行用时：1 ms, 在所有 Java 提交中击败了99.21%的用户
 *     内存消耗：40.8 MB, 在所有 Java 提交中击败了47.25%的用户
 * </pre>
 */
public class No0105 {

    private int[] preorder;

    private Map<Integer, Integer> inorderMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for (int i = 0; i < inorder.length; i++) {
            inorderMap.put(inorder[i], i);
        }

        return recur(0, 0, inorder.length - 1);
    }

    private TreeNode recur(int root, int left, int right) {
        if (left > right) return null;

        int rootVal = preorder[root];
        TreeNode node = new TreeNode(rootVal);

        int rootIdx = inorderMap.get(rootVal);

        node.left = recur(root + 1, left, rootIdx - 1);
        node.right = recur(rootIdx - left + root + 1, rootIdx + 1, right);

        return node;
    }
}
